package com.linght.SpringBoot;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * Description:
 * User:岁亮亮
 * Date:2024-11-06
 * TIME:16:44
 */
@RequestMapping("/CookieAndSession")
@RestController
public class CookieAndSession {

    @RequestMapping("/getCookie")
    public String test1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        StringBuilder stringBuilder = new StringBuilder();
        if(cookies != null) {
           for (Cookie cookie : cookies) {
               stringBuilder.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
           }
        }
        return "Cookie 的信息" + stringBuilder;

    }
    @RequestMapping("/getCookie2")
    public String test4(@CookieValue("username") String uesrname) {
        return "uesrname " + uesrname;

    }

    @RequestMapping("/setSession")
    public String test2(HttpServletRequest request) {
        //通过Cookie中查找到SessionId,再根据SessionId创建Session对象,如果没有获取到创建一个新的Session对象
        HttpSession session = request.getSession();

        if(session != null) {
            session.setAttribute("usermame","sll");

        }
        return "username 存储成功";

    }
    @RequestMapping("/getSession")
    public String test3(HttpServletRequest request) {
        //session为空或者找不到用户信息就重新创建一个session
        HttpSession session = request.getSession();
        String username = null;
        if(session != null && session.getAttribute("usermame") != null) {
            username = (String) session.getAttribute("usermame");
        }
        return username;
    }
    public String test5(@SessionAttribute(value = "username",required = false)String username) {
        return "uesrname " + username;
    }
}
